package cn.e4j.core.util;

import cn.e4j.config.properties.E4jProperties;
import org.apache.poi.ss.formula.functions.T;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class InvokeUtil {

    /**
     * 根据方法名执行方法
     *
     * @param path 'classname,methodname'
     * @param args 参数
     */
    public static <T> T invokeBeanMethod(String path, Object... args) {
        try {

            String[] pathArray = path.split(",");
            Class<Object>[] parameterType = new Class[args.length];
            for (int i = 0; i < args.length; i++) {
                parameterType[i] = (Class<Object>) (args[i]).getClass();
            }

            E4jProperties e4jProperties = E4jProperties.getOWN();

            if(e4jProperties.getDbType().equals("oracle")){
                pathArray[1] = pathArray[1]+"Ora";
            }

            Object tClass = SpringContextHolder.getBean(pathArray[0]);

            return (T) tClass.getClass().getMethod(pathArray[1], parameterType).invoke(tClass, args);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public static <T> T invokeBeanMethod2(String path, Object... args) {
        final Logger logger = LoggerFactory.getLogger(InvokeUtil.class);
        try {

            String methodName = path.substring(path.lastIndexOf(".")+1);
            String fullClassName = path.substring(0, path.lastIndexOf("."));
            String className = fullClassName.substring(fullClassName.lastIndexOf(".")+1);
            String lowerClassName = (className.charAt(0) + "").toLowerCase() + className.substring(1);


            Class<Object>[] parameterType = new Class[args.length];
            for (int i = 0; i < args.length; i++) {
                parameterType[i] = (Class<Object>) (args[i]).getClass();
            }

            E4jProperties e4jProperties = E4jProperties.getOWN();

            if(e4jProperties.getDbType().equals("oracle")){
                methodName = methodName+"Ora";
            }

            Object tClass = SpringContextHolder.getBean(lowerClassName);
//
            return (T) tClass.getClass().getMethod(methodName, parameterType).invoke(tClass, args);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
